package com.bifang.module.file.core.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.domain.AppResponse;
import com.bifang.module.file.common.vo.FileInfoVO;
import com.bifang.module.file.common.vo.FileClassVO;
import com.bifang.module.file.common.vo.FileEnvVO;
import com.bifang.module.file.common.vo.FileUploadResVO;
import com.bifang.module.file.core.biz.FileEnvIntegration;
import com.bifang.module.file.core.biz.FileMoveIntegration;
import com.bifang.module.file.core.common.FileService;
import com.bifang.module.file.core.util.AliOssUtil;
import com.bifang.module.file.core.util.FileCommonUtil;
import com.bifang.module.file.core.util.FileFastDfsUtil;
import com.bifang.module.file.core.util.HttpUtils;
import com.bifang.module.file.dao.service.FileClassService;
import com.bifang.module.file.dao.service.FileInfoService;
import com.bifang.module.file.dao.model.FileClass;
import com.bifang.module.file.dao.model.FileInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FileMoveIntegrationImpl implements FileMoveIntegration {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${system.config.file.url}")
    private String url;

    @Value("${system.config.file.download}")
    private String downloadPath;

    @Autowired
    FileInfoService fileInfoService;
    @Autowired
    FileClassService fileClassService;
    @Autowired
    FileService fileService;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    FileCommonUtil fileCommonUtil;
    @Autowired private FileFastDfsUtil fileFastDfsUtil;
    @Autowired
    FileEnvIntegration fileEnvIntegration;
    // 阿里云服务地址
    private String aliOssUrl = "https://hyt.dongyang.gov.cn/hdFile/api/common/file/move/aliOss";

    @Override
    public void fastdfsToAliOSS(FileInfoVO fileInfoVO) {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().isNull(FileInfo::getRemarks);
        if (fileInfoVO.getFileId() != null) {
            queryWrapper.lambda().eq(FileInfo::getFileId, fileInfoVO.getFileId());
        }
        if (fileInfoVO.getFileStartId() != null && fileInfoVO.getFileEndId() != null) {
            queryWrapper
                    .lambda()
                    .between(
                            FileInfo::getFileId,
                            fileInfoVO.getFileStartId(),
                            fileInfoVO.getFileEndId());
        }
        if (fileInfoVO.getFileId() != null) {
            queryWrapper.lambda().eq(FileInfo::getFileId, fileInfoVO.getFileId());
        }
        if (StringUtils.isNotBlank(fileInfoVO.getShowId())) {
            queryWrapper.lambda().eq(FileInfo::getShowId, fileInfoVO.getShowId());
        }
        if (StringUtils.isNotBlank(fileInfoVO.getFileClassCode())) {
            queryWrapper.lambda().eq(FileInfo::getFileClassCode, fileInfoVO.getFileClassCode());
        }
        if (StringUtils.isNotBlank(fileInfoVO.getRemarks())) {
            queryWrapper.lambda().eq(FileInfo::getRemarks, fileInfoVO.getRemarks());
        }
        List<FileInfo> list = fileInfoService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            for (FileInfo fileInfo : list) {
                File file = null;
                try {
                    FileInfoVO infoVO = Convert.convert(FileInfoVO.class, fileInfo);
                    FileEnvVO fileEnvVO =
                            fileEnvIntegration.getFileEnvDetail(fileInfo.getFileEnvId());
                    BeanUtil.copyProperties(fileEnvVO, infoVO);
                    file = fileFastDfsUtil.download(infoVO);

                    Map<String, Object> formMap = new HashMap<>();
                    formMap.put("fileId", fileInfo.getFileId());
                    String body =
                            HttpUtil.createPost(aliOssUrl)
                                    .form("file", file)
                                    .form(formMap)
                                    .execute()
                                    .body();
                    AppResponse appResponse = JSON.parseObject(body, AppResponse.class);
                    if (appResponse.getCode() == 0) {
                        fileInfo.setRemarks("迁移成功");
                        fileInfoService.updateById(fileInfo);
                    } else {
                        fileInfo.setRemarks("迁移失败:" + appResponse.getMessage());
                        fileInfoService.updateById(fileInfo);
                    }
                } catch (Exception e) {
                    logger.error("文件迁移异常", e);
                } finally {
                    if (file != null) {
                        fileCommonUtil.delTempFile(file);
                    }
                }
            }
        }
    }

    @Override
    public FileUploadResVO upload(
            FileInfoVO fileInfoVO, MultipartFile file, Map<String, String> heardMap) {
        FileUploadResVO fileUploadResVO = new FileUploadResVO();
        fileUploadResVO.setFlag(true);
        FileInfo fileInfo = fileInfoService.getById(fileInfoVO.getFileId());
        if (fileInfo == null) {
            throw new AppException("未找到文件");
        }
        // 获取文件分类信息
        FileClass fileClass = fileClassService.getById(fileInfo.getFileClassCode());
        if (StringUtils.isBlank(fileInfoVO.getFileName())) {
            fileInfoVO.setFileName(file.getOriginalFilename());
        } else {
            if (fileInfoVO.getFileName().indexOf(".") <= 0) {
                throw new AppException("文件名必须包含文件类型后缀");
            }
        }
        FileClassVO fileClassVO = Convert.convert(FileClassVO.class, fileClass);
        BeanUtil.copyProperties(fileInfo, fileInfoVO);
        BeanUtil.copyProperties(fileClassVO, fileInfoVO);
        aliOssUtil.upload(file, fileClassVO, fileInfoVO);
        fileInfo.setFilePath(fileInfoVO.getFilePath());
        fileInfo.setRemarks("迁移成功");
        fileInfoService.updateById(fileInfo);
        return fileUploadResVO;
    }

    @Override
    public void moveCheckFastDFS(FileInfoVO fileInfoVO) {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FileInfo::getRemarks, "迁移成功");
        if (fileInfoVO.getFileStartId() != null && fileInfoVO.getFileEndId() != null) {
            queryWrapper
                    .lambda()
                    .between(
                            FileInfo::getFileId,
                            fileInfoVO.getFileStartId(),
                            fileInfoVO.getFileEndId());
        }
        if (fileInfoVO.getFileId() != null) {
            queryWrapper.lambda().eq(FileInfo::getFileId, fileInfoVO.getFileId());
        }
        if (StringUtils.isNotBlank(fileInfoVO.getShowId())) {
            queryWrapper.lambda().eq(FileInfo::getShowId, fileInfoVO.getShowId());
        }
        if (StringUtils.isNotBlank(fileInfoVO.getFileClassCode())) {
            queryWrapper.lambda().eq(FileInfo::getFileClassCode, fileInfoVO.getFileClassCode());
        }
        List<FileInfo> list = fileInfoService.list(queryWrapper);
        String aliOssShowUrl =
                "https://hyt.dongyang.gov.cn/hdFile/api/common/file/show/hyt_zf_app/";
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        if (!CollectionUtils.isEmpty(list)) {
            for (FileInfo fileInfo : list) {
                String showUrl = aliOssShowUrl + fileInfo.getShowId();
                Map<String, Object> formMap = new HashMap<>();
                count1++;
                try {
                    String s = HttpUtils.doGet(showUrl);
                    if (s.contains("NoSuchKey")) {
                        fileInfo.setRemarks("确认不存在");
                        fileInfoService.updateById(fileInfo);
                        count2++;
                    } else {
                        fileInfo.setRemarks("二次确认成功");
                        fileInfoService.updateById(fileInfo);
                    }
                } catch (Exception e) {
                    fileInfo.setRemarks("确认失败");
                    fileInfoService.updateById(fileInfo);
                    count3++;
                    logger.error("文件确认失败", e);
                }
                System.out.println(
                        fileInfoVO.getFileStartId()
                                + "-----"
                                + fileInfoVO.getFileEndId()
                                + "||||已遍历："
                                + count1
                                + "----已确认不存在"
                                + count2
                                + "----确认失败"
                                + count3);
            }
        }
    }
}
